﻿namespace WMS6.Web.Analytics
{
    using NPOI.HSSF.UserModel;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using WMS6.Web;
    using WMS6.Web.BaseInfoDetailServiceRef;
    using WMS6.Web.BaseInfoServiceRef;
    using WMS6.Web.CommonMethodServiceRef;
    using WMS6.Web.UserControls;

    public class UDFGridReportList : BasePage
    {
        protected HtmlAnchor aaa;
        protected Button btnExport;
        protected Button btnPrint;
        protected HtmlForm F15131;
        protected GridView gvResult;
        protected HtmlInputHidden hdnFrom;
        protected HtmlInputHidden hdnReportID;
        protected HtmlInputHidden hdnReportName;
        protected HtmlInputHidden hdnStatus;
        protected Label lblMsg;
        protected Label lblUDFReportList;
        protected HtmlLink mycss;
        protected Pager PagerFooter;
        protected HtmlAnchor printA;
        protected ScriptManager ScriptManager1;
        protected HtmlGenericControl SideLeftMenu;
        protected UDFReportCtrl UDFReportCtrl1;
        protected UpdatePanel up1;

        private void BindData2gvUDFGridReport(UdfGridReportSettingQueryEntity udfReportQuery)
        {
            DataSet dsUDFReport = BaseInfoServiceClientProxy.GetInstance().GetAllInfo("UDF_GRID_REPORT_SETTING");
            StringBuilder StrHtml = new StringBuilder();
            StrHtml.Append("<dl >");
            for (int i = 0; dsUDFReport.Tables[0].Rows.Count > i; i++)
            {
                StrHtml.AppendFormat(" <dd> <a  href=\"#\"  id=aaa{2}  onclick=\"dd('{0}');\" >{1}</a></dd>", dsUDFReport.Tables[0].Rows[i]["REPORT_ID"], dsUDFReport.Tables[0].Rows[i]["REPORT_NAME"], i);
            }
            StrHtml.Append("</dl>");
            this.SideLeftMenu.InnerHtml = StrHtml.ToString();
        }

        private void BindData2ResultList(WMS6.Web.CommonMethodServiceRef.BaseQuery baseQuery)
        {
            this.PagerFooter.CurrentPage = int.Parse(baseQuery.CurrentPage);
            DataSet ds = CommoneMethodServiceClientProxy.GetInstance().SqlQuery(this.Session["udfReportDataSQL"] as string, baseQuery);
            if (ds != null)
            {
                if (ds.Tables.Count == 1)
                {
                    if (ds.Tables[0].Columns.Contains("ROWSTAT"))
                    {
                        ds.Tables[0].Columns.Remove("ROWSTAT");
                    }
                    this.gvResult.Width = 40 + (ds.Tables[0].Columns.Count * 150);
                    this.gvResult.DataSource = ds.Tables[0];
                    this.gvResult.DataBind();
                }
                if (ds.Tables.Count == 3)
                {
                    if (ds.Tables[2].Columns.Contains("ROWSTAT"))
                    {
                        ds.Tables[2].Columns.Remove("ROWSTAT");
                    }
                    this.gvResult.Width = 40 + (ds.Tables[2].Columns.Count * 150);
                    this.gvResult.DataSource = ds.Tables[2];
                    this.gvResult.DataBind();
                }
            }
            if ((ds != null) && (ds.Tables.Count > 1))
            {
                this.PagerFooter.PageInfo = ds.Tables[1].Rows[0]["CurrentPage"].ToString() + " / " + ds.Tables[1].Rows[0]["TotalPagesCount"].ToString() + "&nbsp;&nbsp;&nbsp;共: " + ds.Tables[1].Rows[0]["TotalRecordsCount"].ToString();
                this.PagerFooter.TotalPages = int.Parse(ds.Tables[1].Rows[0]["TotalPagesCount"].ToString());
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            this.UDFReportCtrl1.GetUdfGridReoprtCtrlValue();
            List<WMS6.Web.BaseInfoDetailServiceRef.UdfGridReportSettingDetailInfo> UdfReportSettingDetailList = this.Session["UdfReportCtrl"] as List<WMS6.Web.BaseInfoDetailServiceRef.UdfGridReportSettingDetailInfo>;
            if (UdfReportSettingDetailList != null)
            {
                UdfGridReportSettingInfo udfReportSettingInfo = BaseInfoServiceClientProxy.GetInstance().GetInfoByID(this.hdnReportID.Value, "UDF_GRID_REPORT_SETTING") as UdfGridReportSettingInfo;
                foreach (WMS6.Web.BaseInfoDetailServiceRef.UdfGridReportSettingDetailInfo info in UdfReportSettingDetailList)
                {
                    udfReportSettingInfo.DataSql = udfReportSettingInfo.DataSql.Replace(info.ParamName, info.Udf1);
                }
                WMS6.Web.CommonMethodServiceRef.BaseQuery baseQuery = this.GetQueryEntity();
                baseQuery.IsGetAll = true;
                string currentPageIndex = baseQuery.CurrentPage;
                baseQuery.CurrentPage = "0";
                try
                {
                    using (DataSet ds = CommoneMethodServiceClientProxy.GetInstance().SqlQuery(this.Session["udfReportDataSQL"] as string, baseQuery))
                    {
                        if (ds.Tables[0].Columns.Contains("ROWSTAT"))
                        {
                            ds.Tables[0].Columns.Remove("ROWSTAT");
                        }
                        this.Export2XLS("udfReport.xls", ds.Tables[0]);
                    }
                }
                finally
                {
                    baseQuery.IsGetAll = false;
                    baseQuery.CurrentPage = currentPageIndex;
                    this.SetQueryEntity(baseQuery);
                }
            }
        }

        protected void btnFirst_Click(object sender, EventArgs e)
        {
            WMS6.Web.CommonMethodServiceRef.BaseQuery baseQuery = this.GetQueryEntity();
            baseQuery.CurrentPage = "0";
            this.BindData2ResultList(baseQuery);
        }

        protected void btnLast_Click(object sender, EventArgs e)
        {
            WMS6.Web.CommonMethodServiceRef.BaseQuery baseQuery = this.GetQueryEntity();
            baseQuery.CurrentPage = (this.PagerFooter.TotalPages - 1).ToString();
            this.BindData2ResultList(baseQuery);
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            WMS6.Web.CommonMethodServiceRef.BaseQuery baseQuery = this.GetQueryEntity();
            if (int.Parse(baseQuery.CurrentPage) < (this.PagerFooter.TotalPages - 1))
            {
                baseQuery.CurrentPage = (int.Parse(baseQuery.CurrentPage) + 1).ToString();
                this.BindData2ResultList(baseQuery);
            }
        }

        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            WMS6.Web.CommonMethodServiceRef.BaseQuery baseQuery = this.GetQueryEntity();
            if (int.Parse(baseQuery.CurrentPage) > 0)
            {
                baseQuery.CurrentPage = (int.Parse(baseQuery.CurrentPage) - 1).ToString();
                this.BindData2ResultList(baseQuery);
            }
        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            if (this.UDFReportCtrl1.GetUdfGridReoprtCtrlValue() != null)
            {
                List<WMS6.Web.BaseInfoDetailServiceRef.UdfGridReportSettingDetailInfo> UdfReportSettingDetailList = this.Session["UdfReportCtrl"] as List<WMS6.Web.BaseInfoDetailServiceRef.UdfGridReportSettingDetailInfo>;
                if (UdfReportSettingDetailList != null)
                {
                    UdfGridReportSettingInfo udfReportSettingInfo = BaseInfoServiceClientProxy.GetInstance().GetInfoByID(this.hdnReportID.Value, "UDF_GRID_REPORT_SETTING") as UdfGridReportSettingInfo;
                    foreach (WMS6.Web.BaseInfoDetailServiceRef.UdfGridReportSettingDetailInfo info in UdfReportSettingDetailList)
                    {
                        udfReportSettingInfo.DataSql = udfReportSettingInfo.DataSql.Replace(info.ParamName, info.Udf1);
                    }
                    WMS6.Web.CommonMethodServiceRef.BaseQuery baseQuery = new WMS6.Web.CommonMethodServiceRef.BaseQuery {
                        IsGetAll = false,
                        CurrentPage = "0",
                        PageSize = this.gvResult.PageSize.ToString(),
                        SortField = "",
                        SortDirection = "ASC"
                    };
                    this.PagerFooter.PageSize = this.gvResult.PageSize;
                    this.Session["udfReportDataSQL"] = udfReportSettingInfo.DataSql;
                    this.SetQueryEntity(baseQuery);
                    this.BindData2ResultList(baseQuery);
                }
            }
        }

        private void Export2XLS(string fileName, DataTable dataTable)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            MemoryStream ms = new MemoryStream();
            HSSFSheet sheet = (HSSFSheet) workbook.CreateSheet("Sheet1");
            HSSFRow headerRow = (HSSFRow) sheet.CreateRow(0);
            try
            {
                foreach (DataColumn column in dataTable.Columns)
                {
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                }
                int rowIndex = 1;
                foreach (DataRow row in dataTable.Rows)
                {
                    HSSFRow dataRow = (HSSFRow) sheet.CreateRow(rowIndex);
                    foreach (DataColumn column in dataTable.Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    }
                    rowIndex++;
                }
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                HttpContext.Current.Response.End();
            }
            finally
            {
                ms.Close();
                ms = null;
                sheet = null;
                headerRow = null;
                workbook = null;
            }
        }

        private void Export2XLS(string fileName, GridView gv)
        {
            gv.Columns[1].Visible = false;
            base.Response.Clear();
            base.Response.Buffer = true;
            base.Response.Charset = "UTF-8";
            base.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString());
            base.Response.ContentEncoding = Encoding.UTF8;
            base.Response.ContentType = "application/ms-excel";
            base.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
            StringWriter sWriter = new StringWriter();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(sWriter);
            gv.RenderControl(htmlWriter);
            string result = Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(sWriter.ToString().Replace("scope=\"col\"", ""), "onmouseout=\"?[^\"]+\"", ""), "onmouseover=\"?[^\"]+\"", ""), "style=\"?[^\"]+\"", ""), "class=\"?[^\"]+\"", ""), "id=\"?[^\"]+\"", ""), "ondblclick=\"?[^\"]+\"", "").Replace("\t", "").Replace("    ", "");
            base.Response.Output.Write(result);
            base.Response.Flush();
            base.Response.End();
            base.Response.Close();
        }

        private WMS6.Web.CommonMethodServiceRef.BaseQuery GetQueryEntity()
        {
            return (base.PageQueryEntitySession as WMS6.Web.CommonMethodServiceRef.BaseQuery);
        }

        private UdfGridReportSettingQueryEntity GetUdfGridReportSettingQueryEntity()
        {
            return (base.PageQueryEntitySession as UdfGridReportSettingQueryEntity);
        }

        protected void GoTo_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(((TextBox) this.PagerFooter.FindControl("txtGo2Page")).Text.Trim()))
            {
                WMS6.Web.CommonMethodServiceRef.BaseQuery baseQuery = this.GetQueryEntity();
                baseQuery.CurrentPage = this.PagerFooter.GoToPage.ToString();
                this.BindData2ResultList(baseQuery);
            }
        }

        protected void gvResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[0].Text = (((this.PagerFooter.CurrentPage * this.PagerFooter.PageSize) + e.Row.RowIndex) + 1).ToString();
            }
        }

        private void LoadData()
        {
            UdfGridReportSettingQueryEntity udfReportQuery = new UdfGridReportSettingQueryEntity {
                IsGetAll = false,
                CurrentPage = "0",
                SortField = "",
                SortDirection = ""
            };
            this.SetUdfGridReportSettingQueryEntity(udfReportQuery);
            this.BindData2gvUDFGridReport(udfReportQuery);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!base.IsPostBack)
            {
                base.InitPage(this.Page);
                this.LoadData();
            }
            string pageSize = base.GetValueFromAppSettings("ANALYTICS_REPORT_LIST_PAGE_COUNT");
            this.gvResult.PageSize = string.IsNullOrEmpty(pageSize) ? 200 : int.Parse(pageSize);
        }

        protected void ReportLoad(object sender, EventArgs e)
        {
            this.UDFReportCtrl1.UdfReportCtrlLoad(this.hdnReportID.Value, "UDF_GRID_REPORT_SETTING");
        }

        private void SetQueryEntity(WMS6.Web.CommonMethodServiceRef.BaseQuery baseQuery)
        {
            base.PageQueryEntitySession = baseQuery;
        }

        public void SetUdfGridReportSettingQueryEntity(UdfGridReportSettingQueryEntity udfReportQuery)
        {
            base.PageQueryEntitySession = udfReportQuery;
        }
    }
}

